<?php
function post($field)
{
	if (!isset($_POST[$field])) return null;
	return $_POST[$field];
}

function step3()
{
	if (!isset($_POST['submit']) || $_POST['submit'] != "Next") goto template;
		
	$errors = 0;
	
	$newdbhost = post('newdbhost');

	$newdbname = post('newdbname');
	if ($newdbname === null) $errors++;
	
	$newdbuser = post('newdbuser');
	if ($newdbuser === null) $errors++;
	
	$newdbpass = post('newdbpass');
	if ($nnewdbpass === null) $errors++;
	
	$newbasedir = post('newbasedir');
	if ($newbasedir === null) $errors++;
	
	$newlogsdir = post('newlogsdir');
	if ($newlogsdir === null) $errors++;
	
	$newuploadsdir = post('newuploadsdir');
	if ($newuploadsdir === null) $errors++;
	
	$newcompanyname = post('newcompanyname');
	if ($newcompanyname === null) $errors++;
	
	$newcompanyurl = post('newcompanyurl');
	if ($newcompanyurl === null) $errors++;
	
	$newdomain = post('newdomain');
	if ($newdomain === null) $errors++;
	
	$newsitename = post('newsitename');
	if ($newsitename === null) $errors++;

	if ($errors > 1) {
		echo $errors;
		echo "All fields are required. Please complete the form in its entirety before continuing to the next step.<br />";
		goto template;
	}

// global $newdbhost, $newdbuser, $newdbpass, $newdbname;
$mysqli = new mysqli($newdbhost, $newdbuser, $newdbpass, $newdbname);

	if ($mysqli->connect_error) {
		die('Error: We could not connect to the database. Please check your database settings and then try again. The error returned was: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
	}

	$file = 'install.sql';
	
	if ($sql = file($file)) {
		$query = '';
		foreach ($sql as $line) {
			$tsl = trim($line);
			if ($sql == '') continue;
			if (substr($tsl, 0, 2) == "--") continue;
			if (substr($tsl, 0, 1) == '#') continue;
			
			$query .= $line;

			if (preg_match('/;\s*$/', $line)) {
			//echo $query;
	
				$statement = $mysqli->stmt_init();
				if ($statement->prepare($query))
					{
					$statement->execute();
				$err = $mysqli->error;
				if (!empty($err)) 
						{
 						echo "An error has occured: " . $err;
						break;
						}
				$query = '';
				//echo "<br>Statement executed successfully!<br><br>";
					$statement->close();
			} else {
 			echo "An error has occured while populating the database: " . $mysqli->error;
			$statement->close();
			}
}
}

		$step3success = true;
}
			$mysqli->close();
	
	template:
	require("step3.tpl");
}
